<!--
  点餐订单
-->
<template>
  <div>
    <!-- 在table中对form进行编辑   -->
    <el-form :model="modelData" ref="modelData" :rules="rules" label-width="120px" :validate-on-rule-change="false">
      <el-card class="card-wrapper">
        <el-row :gutter="20" class="flex-wrap">
          <el-col :span="8">
            <el-form-item label="订单号" prop="orderNo">
              <el-input v-model="modelData.orderNo"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="下单时间" prop="orderTime">
              <el-date-picker type="date" placeholder="选择日期" v-model="modelData.orderTime"
                              style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单类型" prop="orderType">
              <el-select v-model="modelData.orderType" @change="orderTypeChange" placeholder="请选择"
                         style="width: 100%">
                <el-option v-for="item in orderTypes" :label="item.label" :value="item.value"
                           :key="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号" prop="phoneNumber">
              <el-input v-model="modelData.phoneNumber"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="配送地址" prop="address">
              <el-input v-model="modelData.address"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优惠券" prop="couponCode">
              <coupon-info :text.sync="modelData.couponName" :value.sync="modelData.couponCode" @update:value="updateValue"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card class="card-wrapper">
        <el-table :data="tableData" style="width: 100%;margin: 10px 0">
          <el-table-column prop="dishName" label="菜品名称" width="">
          </el-table-column>
          <el-table-column prop="dishPrice" label="菜品价格" width="">
          </el-table-column>
          <el-table-column prop="dishCount" label="菜品价格" width="">
          </el-table-column>
          <el-table-column prop="dishType" label="菜品类目" width="">
          </el-table-column>
          <el-table-column label="Operations">
            <template slot-scope="scope">
              <el-button v-if="!scope.row.editable" size="small" type="text"
                         @click="handleEdit(scope.$index, scope.row)">编辑
              </el-button>
              <el-button v-else size="small" type="text" @click="cancel(scope.$index, scope.row)">取消</el-button>
              <el-button size="small" type="text" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-form :model="tableForm" :rules="rules" ref="tableForm" label-width="120px"
                 :validate-on-rule-change="false">
          <el-row class="flex-wrap" :gutter="20">
            <el-col :span="8">
              <el-form-item label="菜品名称" prop="dishName">
                <el-input v-model="tableForm.dishName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="菜品类目" prop="dishType">
                <el-select v-model="tableForm.dishType" style="width: 100%">
                  <el-option label="酒水" value="1"></el-option>
                  <el-option label="非酒水" value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="菜品价格" prop="dishPrice">
                <el-input v-model="tableForm.dishPrice"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="菜品数量" prop="dishCount">
                <el-input v-model="tableForm.dishCount"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-button style="margin: 10px 0;width: 100%;border: 1px dashed #DCDFE6" type="default" @click="addRow">
              + 添加菜品
            </el-button>
          </el-row>
        </el-form>
      </el-card>
      <el-card class="card-wrapper">
        <el-row class="flex-wrap" :gutter="20">
          <el-col :span="8">
            <el-form-item label="订单总金额" prop="totalAmount">
              <el-input v-model="modelData.totalAmount" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优惠券金额" prop="couponAmount">
              <el-input v-model="modelData.couponAmount" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实付金额" prop="payAmount">
              <el-input v-model="modelData.payAmount"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
    <el-row style="text-align: center">
      <el-button style="margin: 10px" type="primary" size="small" @click="calPrice">价格试算</el-button>
      <el-button style="margin: 10px" type="primary" size="small" @click="submitForm">提交</el-button>
    </el-row>
  </div>
</template>

<script>
import CouponInfo from "@/views/form/components/CouponInfo.vue";

export default {
  components: {CouponInfo},
  data() {
    return {
      tableData: [],
      orderTypes: [
        {label: '堂食', value: 'ts'},
        {label: '外卖', value: 'wm'},
      ],
      modelData: {
        orderNo: null,
        orderTime: null,
        orderType: null,
        phoneNumber: null,
        address: null,
        couponCode: null,
        couponName: null,
        totalAmount: null,
        couponAmount: null,
        payAmount: null,
      },
      tableForm: {
        dishName: '',
        dishPrice: '',
        dishCount: '',
        dishType: '',
        // 是否处于编辑状态
        editable: false,
        key: ''
      },
      rules: {
        // orderNo: [{ required: true, message: '订单号不能为空', trigger: 'blur' }],
        orderTime: [{required: true, message: '下单时间不能为空', trigger: 'blur'}],
        orderType: [{required: true, message: '订单类型不能为空', trigger: 'blur'}],
        phoneNumber: [{required: true, message: '手机号不能为空', trigger: 'blur'}],
        couponCode: [{required: true, message: '优惠券不能为空', trigger: 'blur'}],
        dishName: [{required: true, message: '菜品名称不能为空', trigger: 'blur'}],
        dishPrice: [{required: true, message: '菜品价格不能为空', trigger: 'blur'}],
        dishCount: [{required: true, message: '菜品数量不能为空', trigger: 'blur'}],
        dishType: [{required: true, message: '菜品类目不能为空', trigger: 'blur'}],
        totalAmount: [{required: true, message: '订单总金额不能为空', trigger: 'blur'}],
        couponAmount: [{required: true, message: '优惠券金额不能为空', trigger: 'blur'}],
        payAmount: [{required: true, message: '实付金额不能为空', trigger: 'blur'}],
      }
    }
  },
  mounted() {
    // 测试 reset能否还原对象，是可以的
    console.log({...this.tableForm})
    this.resetForm('tableForm')
    console.log({...this.tableForm})
  },
  methods: {

    orderTypeChange(val) {
      console.log(val)
      if (val === 'wm') {
        this.$set(this.rules, 'address', [{required: true, message: `配送地址不能为空`, trigger: 'blur'}]);
      } else {
        this.$set(this.rules, 'address', null);
      }
    },
    addRow() {
      console.log('form', this.tableForm)
      // 保存信息并重置表单
      this.$refs['tableForm'].validate(valid => {
        if (valid) {
          console.log('add row', {...this.tableForm})
          const curr = this.tableData.find(e => e.editable)
          // 找到处于编辑的值，如果有，则代表是修改
          if (curr) {
            Object.assign(curr, this.tableForm)
          } else {
            // 否则是新增状态，或者是删除过当前编辑的值，都为新增
            // 添加对象
            const data = {...this.tableForm}
            this.tableData.push(data)
            console.log(data.editable)
          }
          // 这个resetForm好像是恢复到上一次form的值，而不是最开始的值
          this.resetForm('tableForm')
          // 这里要重置非表单属性，非表单绑定属性不能还原
          this.tableForm.editable = false
          console.log('after reset', {...this.tableForm})
        } else {
          this.$message.error('请填写完整信息')
        }
      })
    },
    resetForm(formRef) {
      this.$refs[formRef].resetFields()
    },
    /**
     * 将数据赋值给表单，如果保存，将数据回写table，取消则还原数据
     * @param index
     * @param row
     */
    handleEdit(index, row) {
      // table中的数据
      // const td = this.tableData.find((e, idx) => idx === index);
      // todo >> 这里是true，说明当前传入的row就是table中的对象本身
      // console.log('是否是元数据', td === row);
      // 编辑前将其他的先取消编辑
      this.tableData.forEach(e => {
        e.editable = false
      })
      // 保存原始数据 表单是行的原始数据，这里存的是tableData的原始数据，即使在删除状态下，row.editable也是false
      this.tableForm = {...row}
      // 编辑行时，存备份数据（可以省去？），并且设置编辑状态
      // row._data = {...row}
      row.editable = true
      console.log('edit', row, this.tableData[index], this.tableData[index] === row, this.tableForm)
    },
    // 还原数据(是否可以省略？)，重置表单
    cancel(index, row) {
      // 这种直接赋值，不能响应式
      // row = row._data
      // 方式1：这种方式更新对象是响应式的
      // Object.assign(row, row._data)
      // row._data = null;
      // 方式2：更新table数据
      // row = row._data
      // row._data = null;
      // this.$set(this.tableData, index, row);
      this.tableData[index].editable = false
      this.resetForm('tableForm')
      console.log('cancel', row, this.tableData[index])
    },
    handleDelete(index, row) {
      console.log(index, row)
      this.tableData.splice(index, 1)
    },
    // 提交表单，重置主表单和子table
    submitForm() {
      this.$refs['modelData'].validate((valid) => {
        if (valid) {
          console.log('submitForm', {...this.modelData}, this.tableData)
          // this.resetForm('modelData')
          // this.tableData = []
        }
      })
    },
    // 价格试算
    calPrice() {

    },
    updateValue(val) {
      this.modelData.couponCode = val;
      this.$refs['modelData'].clearValidate('couponCode')
    }
  },
  watch: {
    'modelData.couponCode': {
      handler(val) {
        console.log('modelData.couponCode', val)
      }
    }
  }
}
</script>

<style scoped>
/* 可选的样式调整 */
.flex-wrap {
  display: flex;
  flex-wrap: wrap;
}

</style>

<!-- temp style -->
<style scoped>
.el-select .el-input {
  width: 130px;
}

.input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.card-wrapper {
  margin: 10px
}

</style>
